package com.config;

import com.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component  // 标记为 Spring Bea
public class TokenInterceptor implements HandlerInterceptor {

    //private JWTUtil jwtUtil =new JWTUtil();//因为JWT 使用了Spring，因此不能通过new来创建

    private JWTUtil jwtUtil;

    @Autowired
    public TokenInterceptor(JWTUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }

    // 在请求处理之前调用
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //System.out.println("Pre Handle method is Calling");
        String token=request.getHeader("token");
        String newToken = jwtUtil.refreshToken(token);
        if(newToken!=null){
            System.out.println("token更新了");;
            response.setHeader("token",newToken);
            response.setHeader("Access-Control-Expose-Headers", "token"); // 设置暴露的响应头,否则无法打印出来
        }
        // 返回 true，表示请求继续进行，返回 false，表示请求终止
        // 检查是否设置成功
        //System.out.println("Token set in preHandle: " + response.getHeader("token"));
        return true;
    }

    // 在请求处理之后，视图渲染之前调用
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //System.out.println(request.getHeader("token"));
        //response.setHeader("token","newToken0");
        //System.out.println("Post Handle method is Calling");
    }

    // 在整个请求完成之后调用，通常用于资源清理等
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //response.setHeader("token","newToken1");
        //System.out.println("Request and Response is completed");
    }

}
